package com.mills.gamebase.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.mills.gamebase.dao.IRoleDAO;
import com.mills.gamebase.model.Role;

/**
 * Implementierung des Interfaces {@linkplain IRoleDAO}
 * 
 * @author Shane
 *
 */
public class RoleDAO extends AbstractDAO<Role> implements IRoleDAO {

	public RoleDAO () {
		logger = Logger.getLogger(RoleDAO.class);
		entityClazz = Role.class;
		entityModelName = "Role";
	}
	
	@Override
	protected void preload(Role entity, String... preloads) {
		
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public Role getByName(String name, String... preloads) {
		if (name == null) {
			logger.info("Name is null...");
			return null;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Loading Rolle with name = '" + name + "'");
		}

		List<Role> roles = new ArrayList<Role>();
		try {
			roles = (List<Role>) sessionFactory.getCurrentSession().createQuery("select r from Role as r where name like '" + name + "'").list();
		} catch (Exception e) {
			logger.error("Exception caught loading Role with name = '" + name + "':", e);
		}

		if (roles.size() == 0) {
			logger.warn("No Role found with name = '" + name + "'");
			return null;
		}

		return roles.get(0);
	}

	public boolean nameExists(String name, Long id) {
		if (logger.isDebugEnabled()) {
			logger.debug("Checking existence of name '" + name + "'");
		}
		
		try {
			return !sessionFactory.getCurrentSession().createQuery("select r from Role as r where r.name like '" + name + "' and r.id = " + id).list().isEmpty();
		} catch (Exception e) {
			logger.error("Exception caught checking existence of name '" + name + "'!", e);
		}
		
		return false;
	}

}
